package com.alibaba.incubator.loadtestermini.model.load;

import java.util.Random;

import org.springframework.beans.factory.InitializingBean;

/**
 * thread-safe<br/>
 * (created at 2010-5-27)
 * 
 * @author <a href="mailto:shuo.qius@alibaba-inc.com">QIU Shuo</a>
 */
public class ThinkingTime implements InitializingBean {
    private static Random rnd = new Random(System.currentTimeMillis());
    private Integer averageTime;
    private Integer distributionRange;

    public void setAverageTime(Integer averageTime) {
        this.averageTime = averageTime;
    }

    public void setDistributionRange(Integer distributionRange) {
        this.distributionRange = distributionRange;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (averageTime == null)
            throw new IllegalArgumentException("property 'averageTime' is null!");
        if (averageTime < 0)
            averageTime = 0;
        if (distributionRange == null || distributionRange < 0)
            distributionRange = 0;

        int r1 = distributionRange / 2;
        int r2 = distributionRange - r1;
        min = averageTime - r1;
        min = (min < 0) ? 0 : min;
        range = averageTime + r2 - min + 1;
        range = (range < 0) ? 0 : range;
    }

    //-------------------------------------------------------------------------------
    private volatile int min;
    private volatile int range;

    public void thinking() throws InterruptedException {
        int sleepTime = getThinkingTime();
        Thread.sleep(sleepTime);
    }

    private int getThinkingTime() {
        if (range <= 0)
            return min;
        return min + rnd.nextInt(range);
    }
}
